package com.example.tree.service.impl;

import com.example.common.constant.MessageConstant;
import com.example.common.context.BaseContext;
import com.example.common.domain.PageResult;
import com.example.common.exception.BaseException;
import com.example.tree.domain.dto.QueryIssueDTO;
import com.example.tree.domain.dto.TreeIssueDTO;
import com.example.tree.domain.dto.UpdateIssueDTO;
import com.example.tree.domain.po.TreeIssueReport;
import com.example.tree.domain.vo.IssueReportsVO;
import com.example.tree.mapper.TreeIssueMapper;
import com.example.tree.service.TreeIssueService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TreeIssueServiceImpl implements TreeIssueService {
    private ObjectMapper objectMapper = new ObjectMapper();
    private final TreeIssueMapper treeIssueMapper;

    /**
     * 添加古树问题信息
     *
     * @param treeIssueDTO 古树问题信息
     */
    @Override
    public void addTreeIssueInfo(TreeIssueDTO treeIssueDTO) {
        TreeIssueReport treeIssueReport = new TreeIssueReport();
        BeanUtils.copyProperties(treeIssueDTO, treeIssueReport);
        // 将 List<String> 转换为 JSON 字符串
        if (treeIssueDTO.getPhotoUrls() != null) {
            try {
                String photoUrlsJson = objectMapper.writeValueAsString(treeIssueDTO.getPhotoUrls());
                treeIssueReport.setPhotoUrls(photoUrlsJson);
            } catch (JsonProcessingException e) {
                // 处理转换异常
                throw new RuntimeException("Failed to convert photoUrls to JSON", e);
            }
        }

        treeIssueReport.setUserId(BaseContext.getCurrentId());
        treeIssueReport.setReportTime(LocalDateTime.now());
        treeIssueReport.setStatus(0);
        treeIssueMapper.insert(treeIssueReport);
    }

    /**
     * 获取古树问题信息
     *
     * @param queryIssueDTO 查询参数
     * @return 古树问题信息列表
     */
    @Override
    public PageResult<IssueReportsVO> getTreeIssueInfo(QueryIssueDTO queryIssueDTO) {
        TreeIssueReport treeIssueReport = new TreeIssueReport();
        // 将 QueryIssueDTO 转换为 TreeIssueReport
        BeanUtils.copyProperties(queryIssueDTO, treeIssueReport);
        // 获取古树问题信息
        return getIssueReportsVOPageResult(queryIssueDTO.getPageNum(), queryIssueDTO.getPageSize(), treeIssueReport);
    }

    @Override
    public void deleteTreeIssueInfo(Integer[] issueIds) {
        int count = treeIssueMapper.deleteTreeIssueInfo(issueIds);
        if (count < issueIds.length) {
            throw new BaseException(MessageConstant.PARTIAL_NOT_DELETED);
        }
    }

    /**
     * 修改古树问题信息
     *
     * @param updateIssueDTO 修改参数
     */
    @Override
    public void updateTreeIssueInfo(UpdateIssueDTO updateIssueDTO) {
        TreeIssueReport treeIssueReport = new TreeIssueReport();
        BeanUtils.copyProperties(updateIssueDTO, treeIssueReport);
        treeIssueMapper.updateTreeIssueInfo(treeIssueReport);
    }

    @Override
    public List<IssueReportsVO> getUserReportIssue() {
        TreeIssueReport treeIssueReport = TreeIssueReport
                .builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<IssueReportsVO> issueReportsVOList = new ArrayList<>();
        //查询用户上报的异常记录
        List<TreeIssueReport> treeIssueReportList = treeIssueMapper.getTreeIssueInfo(treeIssueReport);
        treeIssueReportList.forEach(issueReport -> {
            IssueReportsVO issueReportsVO = new IssueReportsVO();
            BeanUtils.copyProperties(issueReport, issueReportsVO);
            try {
                // 添加空值检查并提供默认值
                String photoUrlsStr = issueReport.getPhotoUrls();
                if (photoUrlsStr != null && !photoUrlsStr.isEmpty()) {
                    List<String> photoUrls = objectMapper.readValue(photoUrlsStr, List.class);
                    issueReportsVO.setPhotoUrls(photoUrls);
                } else {
                    issueReportsVO.setPhotoUrls(Collections.emptyList()); // 或者 new ArrayList<>()
                }
            } catch (JsonProcessingException e) {
                // 处理转换异常
                throw new RuntimeException("Failed to convert photoUrls to List", e);
            }
            issueReportsVOList.add(issueReportsVO);
        });
        return issueReportsVOList;
    }

    /**
     * 获取古树问题信息
     *
     * @param pageNum         页码
     * @param pageSize        页大小
     * @param treeIssueReport 查询参数
     * @return 古树问题信息列表
     */
    @NotNull
    private PageResult<IssueReportsVO> getIssueReportsVOPageResult(Integer pageNum, Integer pageSize, TreeIssueReport treeIssueReport) {
        // 获取古树问题信息
        PageHelper.startPage(pageNum, pageSize);
        Page<TreeIssueReport> treeIssueReportPage = treeIssueMapper.getTreeIssueInfo(treeIssueReport);
        if (treeIssueReportPage.isEmpty()) {
            return new PageResult<>(0, Collections.emptyList());
        }

        // 使用PageInfo保持分页信息
        Page<IssueReportsVO> resultPage = new Page<>(treeIssueReportPage.getPageNum(), treeIssueReportPage.getPageSize());
        resultPage.setTotal(treeIssueReportPage.getTotal());

        treeIssueReportPage.forEach(issueReport -> {
            IssueReportsVO issueReportsVO = new IssueReportsVO();
            BeanUtils.copyProperties(issueReport, issueReportsVO);
            try {
                // 添加空值检查并提供默认值
                String photoUrlsStr = issueReport.getPhotoUrls();
                if (photoUrlsStr != null && !photoUrlsStr.isEmpty()) {
                    List<String> photoUrls = objectMapper.readValue(photoUrlsStr, List.class);
                    issueReportsVO.setPhotoUrls(photoUrls);
                } else {
                    issueReportsVO.setPhotoUrls(Collections.emptyList()); // 或者 new ArrayList<>()
                }
            } catch (JsonProcessingException e) {
                // 处理转换异常
                throw new RuntimeException("Failed to convert photoUrls to List", e);
            }
            resultPage.add(issueReportsVO);
        });
        PageResult<IssueReportsVO> pageResult = new PageResult<>(resultPage.getTotal(), resultPage.getResult());
        return pageResult;
    }

}
